import axios from 'axios'
import LRU from 'lru-cache'
import qs from 'qs'

const cache = LRU({
  max: 500,
  maxAge: 1000 * 60 * 2
})

const service = axios.create({
  baseURL: 'https://www.luzhongkuan.cn',
  // baseURL: isProd ? 'https://www.luzhongkuan.cn' : 'http://localhost:8002',
  timeout: 15000
})

service.interceptors.request.use(config => {
  config.url = config.url.replace(/^\/api/, '/api/blog')
  return config
})

service.interceptors.response.use(
  response => {
    const { data } = response
    if (data.success) return data
    const err = new Error('接口错误')
    err.response = response
    return Promise.reject(err)
  },
  err => {
    return Promise.reject(err)
  }
)

async function request(data, { isCache = true } = {}) {
  const { url, params = {} } = data
  const cacheKey = `${url}?${qs.stringify(params)}-${data.method || 'get'}`
  let res = isCache ? cache.get(cacheKey) : ''
  if (!res) {
    res = await service(data)
    cache.set(cacheKey, res)
  }
  return res
}

export default request
